package logic

import (
	"context"
	"home-manage/model"
	"time"

	"home-manage/homerpc/homerpc"
	"home-manage/homerpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type AppointmentListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAppointmentListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AppointmentListLogic {
	return &AppointmentListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AppointmentListLogic) AppointmentList(in *homerpc.AppointmentListRequest) (*homerpc.AppointmentListResponse, error) {
	// todo: add your logic here and delete this line

	var appointments []model.AppointmentUser
	tx := model.DB.Debug().Model(&model.Appointment{}).
		Where("appointments.user_id", in.UserId).
		Select("appointments.*,users.tel as user_tel,houses.title as house_name,houses.address as house_address").
		Joins("left join houses on houses.id = appointments.house_id").
		Joins("left join users on users.id =houses.user_id").
		Find(&appointments)
	if in.AppTime == 2 {
		tx.Order("time asc")
	} else {
		tx.Order("time desc")
	}

	tx.Find(&appointments)
	var appointmentList []*homerpc.AppointmentList
	for _, appointment := range appointments {

		list := homerpc.AppointmentList{
			UserId:       int64(appointment.UserId),
			HouseId:      int64(appointment.HouseId),
			Time:         appointment.Time.Format(time.DateTime),
			Name:         appointment.Name,
			Tel:          appointment.Tel,
			HouseName:    appointment.HouseName,
			HouseAddress: appointment.HouseAddress,
		}
		appointmentList = append(appointmentList, &list)
	}
	return &homerpc.AppointmentListResponse{
		List: appointmentList,
	}, nil
}
